package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.ArticleForEsConstants;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.utils.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    WmNewsMaterialService wmNewsMaterialService;

    @Autowired
    WmMaterialService wmMaterialService;

    @Autowired
    WmUserService wmUserService;

    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 查询所有自媒体文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //检查参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        dto.checkParam();

        //封装查询条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //文章标题模糊查询
        wrapper.like(StringUtils.isNotBlank(dto.getKeyword()),WmNews::getTitle,dto.getKeyword());
        // 频道id
        wrapper.eq((dto.getChannelId()!=null),WmNews::getChannelId,dto.getChannelId());
        // 文章状态
        wrapper.eq((dto.getStatus()!=null),WmNews::getStatus,dto.getStatus());
        // 发布时间
        wrapper.ge(  (dto.getBeginPubdate()!=null),WmNews::getPublishTime,dto.getBeginPubdate());
        wrapper.le((dto.getEndPubdate()!=null),WmNews::getPublishTime,dto.getEndPubdate());
        //检查用户id
        wrapper.eq(WmNews::getUserId, user.getId());
        // 分页条件构建
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //执行查询
        page = page(page, wrapper);
        //封装查询结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
        // 处理文章图片
        result.setHost(webSite);
        return result;
    }

    /**
     * 自媒体文章发布
     * @param wmNewsDto
     * @param wmNewsDto 是否为提交 1为提交 0为草稿
     * @return
     */
    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        //校验参数
        if (wmNewsDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //新建wmNews,将保存或修改的参数存入
        WmNews wmNews = new WmNews();
        // 将dto参数里面的值复制到wmNews
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        //如果文章布局是自动，需要设置为null
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }

        // 处理dto参数 images封面集合 转换成 字符串
        String images = imageListToStr(wmNewsDto.getImages(), webSite);
        wmNews.setImages(images);
        saveWmNews(wmNews);
        // 抽取文章中关联的图片路径
        List<Map> contents = JSON.parseArray(wmNewsDto.getContent(), Map.class);
        //文章内图片集合
        List<String> materials = parseContentImages(contents);
        //判读是否有图片
        if (materials.size() > 0) {
            saveRelativeInfoForContent(wmNewsDto,materials,wmNews);
        }
        //判断状态是否为待审核
        if (wmNewsDto.getStatus() == WmNews.Status.SUBMIT.getCode()){
            Map<String,Integer> map = new HashMap();
            map.put(NewsAutoScanConstants.WM_NEWS_ID,wmNews.getId());
            //生产者推送消息
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,JSON.toJSONString(map));
        }

        return ResponseResult.okResult();
    }

    /**
     * 根据id查询wmNews
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //参数检查
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 根据文章id删除文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //参数检查
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取数据,并检查是否存在
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章已发布，不能删除");
        }
        //删除素材与文章的关系
        wmNewsMaterialService.remove(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态，不能上下架");
        }

        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                    .set(WmNews::getEnable,dto.getEnable()));
        }

        //是否上架  0 下架  1 上架
        Map map = new HashMap(1);
        map.put("articleId",wmNews.getArticleId());
        if(dto.getEnable().intValue() == 0){
            kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE,JSON.toJSONString(map));
        }else {
            kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD,JSON.toJSONString(map));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoForContent(WmNewsDto wmNewsDto, List<String> materials,
                                            WmNews wmNews) {
        // 前端用户选择的图
        List<String> images = wmNewsDto.getImages();
        // 自动获取封面
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDto.getType())) {
            int materialSize = materials.size();
            if (materialSize > 0 && materialSize <= 2) {  // 单图
                images =  materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (materialSize > 2) { // 多图
                images =  materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {  // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            if (images != null && images.size() > 0) {
                // 将图片集合 转为字符串  url1,url2,url3
                wmNews.setImages(imageListToStr(images,webSite));
            }
            updateById(wmNews);
        }
        //保存素材和文章关系，抽取一个独立方法执行关联操作，原因当前方法可以复用
        // 保存图片列表和素材的关系
        if (images != null && images.size() > 0) {
            images = images.stream().map(x -> x.replace(webSite, "")
                    .replace(" ", "")).collect(Collectors.toList());
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
    }
    /**
     * 保存素材和文章关系
     * @param materials  素材列表
     * @param newsId     文章ID
     * @param type       类型 0：内容素材  1：封面素材
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        //查询文章内容中的图片对应的素材ID
        List<WmMaterial> dbmaterials = wmMaterialService.list(
                Wrappers.<WmMaterial>lambdaQuery()                                                    	  .in(WmMaterial::getUrl,materials)                                                            .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));

        //校验素材列表
        if (dbmaterials == null || dbmaterials.size() == 0) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        List<Integer> materialIds = new ArrayList<>();
        //{"1.jpg":55,"2.jpg":56}  草稿中的图片列表大于等于 数据库的素材
        Map<String, Integer> matreialMap = dbmaterials.stream()
                .collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

        for (String material : materials) {
            Integer id = matreialMap.get(material);
            if (id == null) { // 数据库中已删除改图片
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            materialIds.add(id);
        }
        // 保存素材关系
        wmNewsMaterialService.saveRelations(materialIds,newsId,type);
    }

    /**
     * 抽取文章内容中 所引用的所有图片
     * @param contents 文章内容
     * @return
     */
    private List<String> parseContentImages(List<Map> contents) {
        // 遍历文章内容   将所有 type为image的 value获取出来  去除前缀路径
        return contents.stream()
                // 过滤type=image所有的集合
                .filter( map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                // 获取到image下的value  图片url
                .map(x -> (String)x.get("value"))
                // 图片url去除前缀
                .map(url-> url.replace(webSite,"").replace(" ",""))
                // sretam 转成list集合
                .collect(Collectors.toList());
    }

    /**
     * 保存或修改文章
     * @param wmNews 文章对象（前端传递）
     * @param wmNews 0 草稿  1 提交审核
     */
    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP); // 上架
        if (wmNews.getId()==null) { // 保存操作
            save(wmNews);
        }else {  // 修改
            // 当前文章 和 素材关系表数据删除
            wmNewsMaterialService.remove(Wrappers
                    .<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }
    /**
     * 图片列表转字符串，并去除图片前缀
     * @param images 图片列表
     * @param webSite 图片前缀
     */
    private String imageListToStr(List<String> images, String webSite) {

        return   images.stream()
                .map(url->url.replace(webSite, ""))//将website去除
                .collect(Collectors.joining(","));//拼接url
    }


    /**
     * 查询需要发布的文章id列表  wm_news   4  8    publishTime < = now()
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        //查询状态为4或为8的数据且发布时间小于当前时间
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery()
                .le(WmNews::getPublishTime, new Date())
                .in(WmNews::getStatus, 4, 8)
                .select(WmNews::getId));

        List<Integer> idList = list.stream().map(WmNews::getId)
                .collect(Collectors.toList());
        return idList;
    }

    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVo> wmNewsVoList = this.baseMapper.findListAndPage(dto);
        //统计多少条数据
        long count = this.baseMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserService.getById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
